package noema.cep;

import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

import noema.dataModel.MyTask;
import noema.dataModel.Patient;

@Stateless
public class PerformActionHelperImpl implements PerformActionHelper {
	
	@PersistenceContext(unitName="application.data")
	private EntityManager em;
	private Logger log=Logger.getLogger(PerformActionHelperImpl.class);

	@Override
	public void addNotificationToHumanTask(String notification, Patient p) {
		Patient p2=em.find(Patient.class, p.getHealthCardId());
		if(p2==null){
			log.error("Notification lost: "+notification+" for "+p);
		}else{
			p=p2;
		}
		Query q=em.createQuery("SELECT t FROM MyTask t, Patient p WHERE p.healthCardId = :patientId AND t.processInstanceId MEMBER OF p.processIds");
		q.setParameter("patientId", p.getHealthCardId());
		for(Object o:q.getResultList()){
			MyTask t=(MyTask)o;
			JSONDeserializer<Map<String, Object>> deserializer=new JSONDeserializer<Map<String,Object>>();
			Map<String,Object> taskParams=deserializer.deserialize(t.getJsonParams());
			int index=0;
			String cepNotificationKey="CEPNotification"+index;
			while(taskParams.containsKey(cepNotificationKey)){
				index++;
				cepNotificationKey="CEPNotification"+index;
			}
			taskParams.put(cepNotificationKey, notification);
			JSONSerializer serializer=new JSONSerializer();
			t.setJsonParams(serializer.deepSerialize(taskParams));
		}
		log.info("Update task for "+p+" with CEP notifiaction "+notification);
		
	}

}
